import { computed, onMounted, reactive, toRefs, watch } from "vue"
import { getCar, delGoodItem } from "@/apis/goods"
import { useStore } from "vuex"
import { useRouter } from "vue-router"
import { Toast } from "vant"
interface stateType {
    checked: any[],
    goodsList: any[],
    allChecked: boolean
}
export default function baseHook() {
    const state: stateType = reactive({
        checked: [],
        goodsList: [],
        allChecked: false//是否全部选中
    })
    const store = useStore()
    const router = useRouter()
    // 监听商品列表选中
    watch(() => state.checked, (newVal) => {
        state.allChecked = state.checked.length === state.goodsList.length
    })


    onMounted(async () => {
        getCarList()
    })

    // 获取商品列表
    const getCarList = async () => {
        const { data } = await getCar()
        state.goodsList = data
        store.commit('cart/upCartList', data)
    }

    const onSubmit = () => {
        if (!state.checked.length) {
            Toast.fail('请选择商品进行结算')
            return
        }
        router.push({ path: '/create-order', query: { cartItemIds: JSON.stringify(state.checked) } })
    }

    // 全选
    const changeAll = () => {
        if (state.allChecked) {
            state.checked = state.goodsList.map((v: any) => v.cartItemId)
        } else {
            state.checked = []
        }
        state.allChecked = !state.allChecked
        // state.goodsList.forEach(v=>v.)
    }

    // 总价
    const total = computed(() => {
        let sum = 0
        let _list = state.goodsList.filter(item => state.checked.includes(item.cartItemId))
        _list.forEach(item => {
            sum += item.goodsCount * item.sellingPrice
        })
        return sum
    })

    // 删除产品
    const delPro = async (id: number) => {
        const { resultCode } = await delGoodItem(id)
        resultCode === 200 && getCarList()
    }


    // 去首页
    const goTo = () => {
        router.push('/')
    }


    return {
        ...toRefs(state), onSubmit, changeAll, total, delPro, goTo
    }
}
